package com.aiyige.page.publish.selectinterest;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.Channel;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.publish.CommonAddDialog;
import com.aiyige.page.publish.selectinterest.adapter.PublishIndustryAdapter;
import com.aiyige.page.publish.selectinterest.adapter.PublishInterestAdapter;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selectteacher.model.TeacherItem;
import com.aiyige.page.selectinterest.model.IndustryItem;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Route(path = ARouterConfig.PublishSelectInterestPage)
public class PublishSelectInterestPage extends AppCompatActivity {
    public static final String EXTRA_KEY_SELECTED_ID = "com.aiyige.extra.EXTRA_KEY_SELECTED_ID";
    public static final String EXTRA_KEY_SELECTED_TITLE = "com.aiyige.extra.EXTRA_KEY_SELECTED_TITLE";
    public static final String EXTRA_KEY_SELECTED_PARENT_ID = "com.aiyige.extra.EXTRA_KEY_SELECTED_PARENT_ID";
    public static final String EXTRA_KEY_SELECTED_PARENT_TITLE = "com.aiyige.extra.EXTRA_KEY_SELECTED_PARENT_TITLE";

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.industryRv)
    RecyclerView industryRv;
    @BindView(R.id.interestRv)
    RecyclerView interestRv;
    List<PublishIndustryItem> publishIndustryItemList;
    PublishIndustryAdapter publishIndustryAdapter;
    PublishInterestAdapter publishInterestAdapter;
    CommonAddDialog commonAddDialog;
    PublishIndustryItem currentPublishIndustry = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_select_interest);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.interest_category);
        publishIndustryItemList = new LinkedList<>();
        commonAddDialog = CommonAddDialog.newInstance(R.string.add_interest_category, R.string.please_input_interest_category, 15);
        commonAddDialog.setListener(new CommonAddDialog.Listener() {
            @Override
            public void onOk(String str) {
                doAddInterest(currentPublishIndustry, str);
            }

            @Override
            public void onCancel() {

            }
        });


        industryRv.setLayoutManager(new LinearLayoutManager(this));
        interestRv.setLayoutManager(new LinearLayoutManager(this));
        publishIndustryAdapter = new PublishIndustryAdapter();
        publishIndustryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                doSelectIndustry(publishIndustryAdapter.getItem(position));
            }
        });
        publishInterestAdapter = new PublishInterestAdapter();
        publishInterestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PublishInterestItem publishInterestItem = publishInterestAdapter.getItem(position);
                switch (publishInterestItem.getType()) {
                    case PublishInterestItem.TYPE_ADD: {
                        currentPublishIndustry = publishInterestItem.getParent();
                        commonAddDialog.show(getSupportFragmentManager(), "");
                        break;
                    }
                    case PublishInterestItem.TYPE_NORMAL:
                    case PublishInterestItem.TYPE_SELECT_ALL: {
                        doSelectInterest(publishInterestItem);
                        break;
                    }
                }
            }
        });
        industryRv.setAdapter(publishIndustryAdapter);
        interestRv.setAdapter(publishInterestAdapter);
        requestData();
    }


    public PublishInterestItem checkDuplicate(PublishIndustryItem publishIndustryItem, String title) {
        PublishInterestItem duplicateItem = null;
        for (PublishInterestItem item : publishIndustryItem.getPublishInterestItemList()) {
            if (item.getType() == PublishInterestItem.TYPE_NORMAL && item.getTitle().equals(title)) {
                duplicateItem = item;
                break;
            }
        }
        return duplicateItem;
    }


    public void doAddInterest(PublishIndustryItem publishIndustryItem, String title) {
        PublishInterestItem item = checkDuplicate(publishIndustryItem, title);
        if (item != null) {
            doSelectInterest(item);
            return;
        }

        new AsyncTask<Object, Object, Object>() {
            LoadingDialog loadingDialog;

            @Override
            protected void onPreExecute() {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(PublishSelectInterestPage.this)
                        .message(R.string.text_process)
                        .show();
            }

            @Override
            protected Object doInBackground(Object... params) {
                try {
                    PublishIndustryItem parent = (PublishIndustryItem) params[0];
                    String title = (String) params[1];
                    Response<ResponseBody> response = ApiManager.getService().createUserTag(Tag.newBuilder()
                            .groupType(SetupUtil.GROUP_TYPE_CATEGORY)
                            .channel(parent.getId())
                            .name(title)
                            .creator(AccountUtil.getCurrentUser().getId())
                            .build())
                            .execute();
                    if (response.code() != ResponseCode.CREATED) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Tag tag = JSON.parseObject(json, Tag.class);
                    return PublishInterestItem.newBuilder()
                            .id(tag.getId())
                            .title(tag.getName())
                            .parent(parent)
                            .build();
                } catch (Exception e) {
                    return e;
                }
            }

            @Override
            protected void onPostExecute(Object o) {
                loadingDialog.dismiss();
                if (o instanceof PublishInterestItem) {
                    doSelectInterest((PublishInterestItem) o);
                } else if (o instanceof Exception) {
                    ToastX.show(((Exception) o).getMessage());
                } else {
                    ToastX.show(R.string.add_failed);
                }
            }
        }.execute(publishIndustryItem, title);


    }

    public void requestData() {
        ApiManager.getService()
                .allChannel(BuildConfig.appVersion)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.code() != ResponseCode.OK) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            }
                            String json = RetrofitUtil.getResponseBodyAsString(response);
                            List<Channel> channelList = JSON.parseArray(json, Channel.class);
                            for (Channel channel : channelList) {
                                PublishIndustryItem publishIndustryItem = PublishIndustryItem.newBuilder()
                                        .id(channel.getId())
                                        .title(channel.getName())
                                        .build();
                                publishIndustryItemList.add(publishIndustryItem);
                            }
                            if (!ListUtil.isEmpty(publishIndustryItemList)) {
                                publishIndustryAdapter.setNewData(publishIndustryItemList);
                                doSelectIndustry(publishIndustryItemList.get(0));
                            }
                        } catch (Exception e) {
                            onFailure(call, e);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        ToastX.show(t.getMessage());
                    }
                });
    }

    public void doSelectIndustry(PublishIndustryItem item) {
        if (ListUtil.isEmpty(item.getPublishInterestItemList())) {
            new RequestInterestTask().execute(item);
        } else {
            clearIndustrySelect();
            item.setSelected(true);
            publishIndustryAdapter.notifyDataSetChanged();
            publishInterestAdapter.setNewData(item.getPublishInterestItemList());
        }
    }

    private class RequestInterestTask extends AsyncTask<PublishIndustryItem, Object, Object> {
        LoadingDialog loadingDialog;
        PublishIndustryItem publishIndustryItem;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishSelectInterestPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(PublishIndustryItem... params) {
            publishIndustryItem = params[0];
            Response<ResponseBody> response;
            try {
                response = ApiManager.getService()
                        .getSetup(SetupUtil.GROUP_TYPE_CATEGORY, BuildConfig.appVersion, publishIndustryItem.getId())
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    List<Setup> setupList = JSON.parseArray(json, Setup.class);
                    for (Setup setup : setupList) {
                        publishIndustryItem.getPublishInterestItemList().add(PublishInterestItem.newBuilder()
                                .id(setup.getId())
                                .title((String) setup.getData().get("name"))
                                .parent(publishIndustryItem)
                                .build());
                    }
                }
                response = ApiManager.getService()
                        .getUserTag(AccountUtil.getCurrentUser().getId(), publishIndustryItem.getId(), SetupUtil.GROUP_TYPE_CATEGORY)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    List<Tag> tagList = JSON.parseArray(json, Tag.class);
                    for (Tag tag : tagList) {
                        publishIndustryItem.getPublishInterestItemList().add(PublishInterestItem.newBuilder()
                                .id(tag.getId())
                                .title(tag.getName())
                                .parent(publishIndustryItem)
                                .build());
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
                publishIndustryItem.setPublishInterestItemList(new LinkedList<PublishInterestItem>());
            } else {
                clearIndustrySelect();
                publishIndustryItem.setSelected(true);
                publishIndustryAdapter.notifyDataSetChanged();
                publishIndustryItem.getPublishInterestItemList().add(0, PublishInterestItem.newBuilder()
                        .parent(publishIndustryItem)
                        .type(PublishInterestItem.TYPE_SELECT_ALL)
                        .build());
                publishIndustryItem.getPublishInterestItemList().add(PublishInterestItem.newBuilder()
                        .parent(publishIndustryItem)
                        .type(PublishInterestItem.TYPE_ADD)
                        .build());
                publishInterestAdapter.setNewData(publishIndustryItem.getPublishInterestItemList());
            }
        }
    }


    public void doSelectInterest(PublishInterestItem item) {
        Intent intent = new Intent();
        switch (item.getType()) {
            case PublishInterestItem.TYPE_NORMAL:
                intent.putExtra(EXTRA_KEY_SELECTED_PARENT_ID, item.getParent().getId());
                intent.putExtra(EXTRA_KEY_SELECTED_PARENT_TITLE, item.getParent().getTitle());
                intent.putExtra(EXTRA_KEY_SELECTED_ID, item.getId());
                intent.putExtra(EXTRA_KEY_SELECTED_TITLE, item.getTitle());
                break;
            case PublishInterestItem.TYPE_SELECT_ALL:
                intent.putExtra(EXTRA_KEY_SELECTED_PARENT_ID, item.getParent().getId());
                intent.putExtra(EXTRA_KEY_SELECTED_PARENT_TITLE, item.getParent().getTitle());
                intent.putExtra(EXTRA_KEY_SELECTED_ID, item.getParent().getId());
                intent.putExtra(EXTRA_KEY_SELECTED_TITLE, item.getParent().getTitle());
                break;
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    public void clearIndustrySelect() {
        for (PublishIndustryItem publishIndustryItem : publishIndustryItemList) {
            publishIndustryItem.setSelected(false);
        }
    }

    @OnClick({R.id.titleBackBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn: {
                setResult(RESULT_CANCELED);
                finish();
                break;
            }
        }
    }
}
